import config from "@/config/config.js";
import cookie from "@/util/store/cookie"
import stringify from "@/util/querystring";

const baseURL = config.apiRoot;

const token = 'token'

//获取token
function getToken() {
	return cookie.get(token);

}

//发送请求
function request(options) {
	// console.log(options);
	return new Promise((resolve, reject) => {

		//判断dataType不存在或为空则设置为json格式
		if (!options.dataType) {
			options.dataType = 'json'
		}

		//判断参数不存在或为空则设置为空对象
		if (options.params) {
			options.url += '?' + stringify(options.params)
		}

		//请求头
		const header = {
			'Content-Type': "application/json",
			...options.header,
		}

		if (getToken()) {
			header['authorization'] = getToken();
		}
		// console.log(header);
		uni.request({
			url: baseURL + options.url, //仅为示例，并非真实接口地址。
			data: options.data,
			method: options.method,
			header: header,
			dataType: options.dataType,
			success: (res) => {
				var result = res.data;
				// console.log(result)

				if (result.code == 200) {
					resolve(result);
				} else if (result.code == 403) {
					cookie.remove('token');
					uni.showToast({
						title: result.msg,
						icon: 'error'
					});
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/index'
						});
					}, 500);

				} else if (result.code == 402) {
					uni.showToast({
						title: result.msg,
						icon: 'error'
					});
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/index/bind-tel'
						});
					}, 500);
				} else {
					// showToast(result.msg);
					resolve(result);
				}
			},
			fail: (err) => {
				let errMsg = "";
				if (err != undefined && err.errMsg != undefined) {
					errMsg = error.errMsg;
				}
				showToast("连接失败：服务器出错:" + errMsg);
				reject();
			}
		});
	}).catch((e) => {
		console.log(e);
	})

}
//提示信息
export function showToast(title, position = "center", icon = "none", duration = 2000) {
	uni.showToast({
		title,
		position,
		icon,
		duration
	});
}

export default request
